///<reference path="bluelotus7.common.js" />
var currentDomainScopeKey, currentDomainScopeUserKey, currentViewType, currentStartDate, currentEndDate;

function bindDomainScopesListEvent(domainScopesList, domainScopeUserList) {
    if (!domainScopesList) {
        domainScopesList = $("#domainScopeList");
    }
    if (!domainScopeUserList) {
        domainScopeUserList = $("#domainScopeUserList");
    }
    domainScopesList.bind("change", { userList: domainScopeUserList }, function (e) {
        fillDomainScopeUsersByScopeKey(e.data.userList, $(this).val(), false);
    });
    if (domainScopesList.children("option").length = 1) {
        domainScopesList.change();
    }
}

function fillDomainScopeUsersByScopeKey(selectObject, key, hasEmpty) {
    if (selectObject) {
        selectObject.children("option").remove();

        var maskField = bluelotus7.mask($("#queryPanel"), "Loading domain scope users...");
        $.ajax({
            url: appendRandom(ajaxCollection["GetUserListByDomainScopeKey"] + "?key=" + key),
            type: 'GET',
            async: false,
            contentType: 'application/json',
            dataType: 'json',
            success: function (result) {
                if (result && result.IsSuccess) {
                    window.dataSource.fillComboSource(selectObject, result.Data.Items);
                    if (hasEmpty) {
                        selectObject.prepend($("<option value=''> </option>"));
                    }
                }

                bluelotus7.unmask(maskField);
            }
        });

    }
}

function bindCheckBoxEventForMerge(tbodyObject) {
    if (tbodyObject) {
        tbodyObject.find("tr > td.selectable > input:checkbox").bind("click", { gridBody: tbodyObject }, function (e) {
            tbodyObject.children("tr").remove("selectable");
            var rangeItems = getSelectionEffectRange(tbodyObject);
            $(rangeItems).cloest("tr").addClass("selectable");
        });
    }
}

function getSelectionRange(tbodyObject) {
    var result = new Array();
    if (tbodyObject) {
        var checkBoxes = tbodyObject.children("tr > td.selectable > input:checkbox");
        var checkedBoxes = checkBoxes.filter(":checked");
        if (checkedBoxes && checkedBoxes.length) {
            var first = checkedBoxes.filter(":first");
            var last = checkedBoxes.filter(":last");
            for (var i = checkBoxes.index(first); i < checkBoxes.index(last); i++) {
                result.push(checkBoxes.eq(i));
            }
        }
    }
    return result;
}

function queryStatusByCriterias(container) {
    if (!container) {
        container = $("#queryPanel");
    }

    currentDomainScopeKey = $("#domainScopeList").val();
    currentDomainScopeUserKey = $("#domainScopeUserList").val();
    currentStartDate = $("#queryPanelStartDate input").val();
    currentEndDate = $("#queryPanelEndDate input").val();
    currentViewType = $("#statusViewList").val();

    if (currentDomainScopeUserKey) {
        refreshStatusGrid();
    }
}

function refreshStatusGrid(container, mergeStatusList) {
    if (!container) {
        container = $("#queryResult");
    }
    if (!mergeStatusList) {
        mergeStatusList = $("#statusList");
    }


    var maskField = bluelotus7.mask(container, "Retrieving data...");
    var postData = {
        DomainScopeKey: currentDomainScopeKey,
        DomainScopeUserKey: currentDomainScopeUserKey,
        StartStamp: currentStartDate,
        EndStamp: currentEndDate
    };

    $.ajax({
        url: appendRandom(ajaxCollection[(currentViewType == 0 ? "QueryStatusGridByCriterias" : "QueryStatusCalendarByCriterias")]),
        type: 'POST',
        async: false,
        data: JSON.stringify(postData),
        contentType: 'application/json',
        //dataType: 'json',
        success: function (result) {
            if (result) {
                container.children().remove();
                container.append(result);
                if (currentViewType == 0 && mergeStatusList) {
                    $("#statusMergePanel").show();
                    mergeStatusList.children().remove();
                    mergeStatusList.append(dataSource.getComboSource(currentDomainScopeKey).children());
                    initMerge(container.find("table:last"));
                }
                else {
                    $("#statusMergePanel").hide();
                }
            }

            bluelotus7.unmask(maskField);
        }
    });
}

function initMerge(gridObject) {
    if (gridObject) {
        tbodyObject = gridObject.find("tbody:last");
        var checkboxes = tbodyObject.find("td.selectable > input:checkbox");
        checkboxes.bind("click", { tbody: tbodyObject, checkboxes: checkboxes }, function (e) {
            e.data.tbody.children("tr").removeClass("selected");
            var range = handleMergeRange(e.data.tbody);
            if (range.first && range.last) {
                var firstIndex = e.data.checkboxes.index(range.first);
                var lastIndex = e.data.checkboxes.index(range.last);

                for (var i = firstIndex; i <= lastIndex; i++) {
                    e.data.checkboxes.eq(i).closest("tr").addClass("selected");
                }
            }
        });
    }
}

function handleMergeRange(tbodyObject) {
    var result = { firstGuid: undefined, lastGuid: undefined };
    if (tbodyObject) {
        var checkboxes = tbodyObject.find("td.selectable > input:checked");
        result.first = checkboxes.filter(":first");
        result.firstGuid = result.first.attr("value");
        result.last = checkboxes.filter(":last");
        result.lastGuid = result.last.attr("value");
    }
    return result;
}
function mergeStatus(gridObject, status) {
    if (gridObject) {
        tbodyObject = gridObject.find("tbody:last");
        var result = handleMergeRange(tbodyObject);

        if (result.firstGuid && result.lastGuid) {
            if (result.firstGuid == result.lastGuid) {
                alert("Please select at least two items");
                return;
            }

            if (confirm("Are you sure to merge these status?")) {
                var postData = { DomainScopeUserKey: currentDomainScopeUserKey, Status: status, StartGuid: result.lastGuid, EndGuid: result.firstGuid };
                var maskField = bluelotus7.mask();
                $.ajax({
                    url: appendRandom(ajaxCollection["MergeStatus"]),
                    type: 'POST',
                    async: false,
                    data: JSON.stringify(postData),
                    contentType: 'application/json',
                    dataType: 'json',
                    success: function (result) {
                        if (result && result.IsSuccess) {
                            refreshStatusGrid();
                        }

                        bluelotus7.unmask(maskField);
                    }
                });
            }
        }
    }
}
